<?php
/**
 * Created by PhpStorm.
 * User: JX
 * Date: 2017/8/8
 * Time: 9:47
 */

namespace App\Http\Controllers;

use App\Models\AdminLog;
use App\Models\WeChat;
use App\Models\WechatArticle;
use App\Models\WechatArtLog;
use App\Models\WechatCumulative;
use App\Models\WeChatImgLog;
use App\Models\WeChatImgSource;
use App\Models\WechatMassLog;
use App\Models\WechatMessage;
use App\Models\WechatUser;
use Illuminate\Support\Facades\Auth;
use App\Models\WechatUserRecord;
use App\Models\WechatUserRelation;
use App\Models\WechatVideoLog;
use App\Models\WechatVideoSource;
use App\Models\WechatVoiceLog;
use App\Models\WechatVoiceSource;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Material;
use EasyWeChat\Message\Article;
use EasyWeChat\Message\Image;
use EasyWeChat\OpenPlatform\Guard;
use GuzzleHttp\Promise\RejectionException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Doctrine\Common\Cache\PredisCache;
use GuzzleHttp\Client;
use EasyWeChat\Message\Text;

class WechatController extends Controller
{

    private $app_id;
    public $days = array();
    private $openPlatform = '';

    public function __construct(Application $app)
    {
        $predis = app('redis')->connection()->client();// connection($name), $name 默认为 `default`
        $cacheDriver = new PredisCache($predis);
        $app->cache = $cacheDriver;
        $this->openPlatform = $app->open_platform;
        $BeginDate = date('Y-m-01', strtotime(date("Y-m-d")));
        $time = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
        $start = date('t', time()) - 1;
        for ($i = $start; $i >= 0; $i--) {
            $this->days[] = date('Y-m-d', strtotime($time . ' -' . $i . 'day'));
        }
    }

    /**
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     * 获取授权地址
     */
    public function getLink()
    {
        $openPlatform = $this->openPlatform;
        $response = $openPlatform->pre_auth->redirect('http://tjise.daxuefun.cn/wechat/back');
// 获取跳转的 URL
        return $response;
    }

    /**
     * 第三方开放平台授权地址
     * 每隔10分钟会更新一次预授权码
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function authcallback(Request $request)
    {
        $openPlatform = $this->openPlatform;
        $server = $openPlatform->server;
        $server->setMessageHandler(function ($event) use ($openPlatform) {
            // 事件类型常量定义在 \EasyWeChat\OpenPlatform\Guard 类里
            switch ($event->InfoType) {
                case Guard::EVENT_AUTHORIZED: // 授权成功
                    $authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
                    \Log::info($authorizationInfo);
                    \Log::info('授权成功');
                    $info = $authorizationInfo->toArray();
                    $this->AddUser($info['authorization_info']['authorizer_appid']);
                    break;
                // 保存数据库操作等...
                case Guard::EVENT_UPDATE_AUTHORIZED: // 更新授权
                    // 更新数据库操作等...
                    $authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
                    \Log::info($authorizationInfo);
                    \Log::info('更新授权');
                    $info = $authorizationInfo->toArray();
                    $this->AddUser($info['authorizer_appid']);
                    break;
                case Guard::EVENT_UNAUTHORIZED: // 授权取消
                    //\Log::info(var_dump($event));
                    // 更新数据库操作等...
//                        $authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
//                        $info = $authorizationInfo->toArray();
//                        $this->AddUser($info['authorizer_appid']);
                    \Log::info($event);
                    $appId = $event->AuthorizerAppid;
                    $wechat = WeChat::query()->where(['authorizer_appid' => $appId])->first();
                    \Log::info($wechat->nick_name . '授权取消');
                    if ($wechat) {
                        $wechat->delete();
                    }
                    \Log::info('授权取消');
                    break;
                case Guard::EVENT_COMPONENT_VERIFY_TICKET:
                    //推送预授权码
                    \Log::info('推送ComponentVerifyTicket');
                    $appId = $event->AppId;
                    $componentVerifyTicket = $event->ComponentVerifyTicket;
                    \Log::info([
                        'app_id' => $appId,
                        'component_verify_ticket' => $componentVerifyTicket
                    ]);
                    \Cache::put('component-verify-ticket', $componentVerifyTicket, 10);
                    break;
                default;
                    return redirect('http://tjise.daxuefun.cn/#/wechat/list');
            }
        });
        $response = $server->serve();
        return $response;
    }

    /**
     * @param $authorizerAppId
     * 更新公众号信息
     */
    public function AddUser($authorizerAppId)
    {
        // $authorizerAppId = 'wxa809db2a64aa8ecd';
        $openPlatform = $this->openPlatform;
        $user = $openPlatform->getAuthorizerInfo($authorizerAppId);
        $wechat = WeChat::query()->where(['authorizer_appid' => $user['authorization_info']['authorizer_appid']])->first();
        if (!$wechat) {
            $wechat = new WeChat();
        }
        $img = $this->GrabImage($user['authorizer_info']['qrcode_url']);
        $wechat->nick_name = $user['authorizer_info']['nick_name'];
        $wechat->authorizer_appid = $user['authorization_info']['authorizer_appid'];
        $wechat->authorizer_refresh_token = $user['authorization_info']['authorizer_refresh_token'];
        $wechat->service_type_info = json_encode($user['authorizer_info']['service_type_info']);
        $wechat->verify_type_info = json_encode($user['authorizer_info']['verify_type_info']);
        $wechat->user_name = $user['authorizer_info']['user_name'];
        $wechat->qrcode_url = $img;
        $wechat->principal_name = $user['authorizer_info']['principal_name'];
        $wechat->signature = $user['authorizer_info']['signature'];
        if (!$wechat->save()) {
            dd($wechat->getErrors());
        }
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * 授权返回界面
     */
    public function back()
    {
        return redirect('http://tjise.daxuefun.cn/#/wechat/list');

    }

    /**
     * @param Request $request
     * @param $appId
     * 回掉函数
     */
    public function callback(Request $request, $appId)
    {
        $wechat = WeChat::query()->where(['authorizer_appid' => $appId])->first();
        $this->app_id = $wechat->id;
        $openPlatform = $this->openPlatform;
        $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
        $server = $app->server;
        $userService = $app->user;
        $server->setMessageHandler(function ($message) use ($userService, $appId) {
            // 注意，这里的 $message 不仅仅是用户发来的消息，也可能是事件
            // 当 $message->MsgType 为 event 时为事件
            \Log::info($message);
            if ($message->FromUserName) {
                \DB::beginTransaction();
                try {
                    $user = $userService->get($message->FromUserName);
                    \Log::info($message->FromUserName);
                    $wechat_user = WechatUser::withTrashed()->where(['open_id' => $user->openid])->first();
                    if ($user->subscribe == 1) {
                        if (!$wechat_user) {
                            $wechat_user = new WechatUser();
                        }
                        //$user=$user->all();
                        $wechat_user->w_id = $this->app_id;
                        $wechat_user->nick_name = $user->nickname;
                        $wechat_user->sex = $user->sex;
                        $wechat_user->city = $user->city;
                        $wechat_user->country = $user->country;
                        $wechat_user->province = $user->province;
                        $wechat_user->headimgurl = $user->headimgurl;
                        $wechat_user->open_id = $user->openid;
                        $wechat_user->subscribe_time = $user->subscribe_time;
                        $wechat_user->remark = $user->remark;
                        $wechat_user->deleted_at = null;
                        $wechat_user->groupid = $user->groupid;
                        $wechat_user->tagid_list = empty($user->tagid_list) ? '' : json_encode($user->tagid_list);
                        if (!$wechat_user->save()) {
                            throw  new \Exception('用户添加失败');
                        }
                        switch ($message->MsgType) {
                            case 'text';
                                $this->replyMessage($appId, $user->openid, $message->Content);
                                $new_message = new WechatMessage();
                                $new_message->user_open_id = $wechat_user->id;
                                $new_message->type = 1;
                                $new_message->CreateTime = $message->CreateTime;
                                $new_message->MsgId = $message->MsgId;
                                $new_message->w_id = $this->app_id;
                                $new_message->content = $message->Content;
                                if (!$new_message->save()) {
                                    throw  new \Exception('文字消息保存失败');
                                }
                                break;
                            case 'image';
                                $img = $this->GrabImage($message->PicUrl);
                                $new_message = new WechatMessage();
                                $new_message->user_open_id = $wechat_user->id;
                                $new_message->PicUrl = $img;
                                $new_message->MediaId = $message->MediaId;
                                $new_message->type = 2;
                                $new_message->CreateTime = $message->CreateTime;
                                $new_message->MsgId = $message->MsgId;
                                $new_message->w_id = $this->app_id;
                                if (!$new_message->save()) {
                                    throw  new \Exception('图片消息保存失败');
                                }
                                break;
                        }
                        if ($message->MsgType == 'event') {
                            # code...
                            switch ($message->Event) {
                                case 'subscribe';
                                    # code...
                                    break;
                                case 'CLICK';
                                    if ($message->EventKey) {
                                        $this->replyMessage($appId, $user->openid, $message->EventKey);
                                    }
                                    break;
                                default;
                                    # code...
                                    break;
                            }
                        }
                    } else {
                        if ($wechat_user) {
                            if ($wechat_user->delete()) {
                                \Log::info('用户已取消关注');
                            }
                        }
                        // throw  new \Exception('用户已取消关注');
                    }
                    \DB::commit();
                } catch (\Exception $e) {
                    \DB::rollBack();
                    \Log::info($e->getMessage());
                }

            }


        });
        $response = $server->serve();
        $response;
    }

    /**
     * @param $w_id
     * @return mixed
     * 菜单获取
     */
    public function getMenu($w_id)
    {
        $wechat = WeChat::query()->where(['id' => $w_id])->first();
        $openPlatform = $this->openPlatform;
        $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
        $menu = $app->menu;
        $list = $menu->current();
        $botton = $list['selfmenu_info']['button'];
        $res = [];
        foreach ($botton as $item) {
            if (!isset($item['sub_button'])) {
                $item['sub_button'] = [];
            } else {
//                dd($item['sub_button']);
                $item['sub_button'] = $item['sub_button']['list'];
            }
            $res[] = $item;
        }
        //   dd($res);
        return $res;
    }

    /**
     * @param Request $request
     * @return \EasyWeChat\Support\Collection
     * 更新菜单
     */
    public function newMenu(Request $request)
    {
        $w_id = $request->get('id');
        $new_menu = $request->get('menu');
        //   dd(json_decode($new_menu));
        $wechat = WeChat::query()->where(['id' => $w_id])->first();
        $openPlatform = $this->openPlatform;
        $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
        $menu = $app->menu;
        $menu->destroy();
        $res = $menu->add(json_decode($new_menu));

        return $res;
    }

    /**
     * @param Request $request
     * @return array
     * 获取统计信息
     */
    public function getStatistics(Request $request)
    {
        $w_id = $request->get('w_id');
        $result = [];
        $arr = ['1' => '关注数', '2' => '取消数', '3' => '净增关注', '4' => '累计关注'];
        foreach ($arr as $key => $item) {
            $res['type'] = 'line';
            $res['name'] = $item;
            $res['data'] = $this->getRecordsByDays($w_id, $key);
            $result['data'] [] = $res;
        }
        $result ['time'] = $this->days;
        return $result;
    }

    /**
     * @param Request $request
     * @return null
     *获取昨日数据
     */
    public function getElements(Request $request)
    {
        $w_id = $request->get('w_id');
        $result = null;
        $time = date('Y-m-d', strtotime(" -1 day"));
        $yesterday = date('Y-m-d', strtotime(" -2 day"));
        $last_week = date('Y-m-d', strtotime(" -1 week"));
        $ThisMonday = (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600);
        $ThisSunDay = (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600);
        $LastMonday = strtotime('-1 monday', time());
        $LastSunDay = strtotime('-1 sunday', time());
        $new = $this->getNewUserRecords($w_id, $time);
        $cancel = $this->getCancelUserRecords($w_id, $time);
        $result['new']['number'] = $new;
        $result['new']['day'] = $this->inputElement($new, $this->getNewUserRecords($w_id, $yesterday), '日');
        $result['new']['week'] = $this->inputElement($this->getWeekNewUserRecords($w_id, $ThisMonday, $ThisSunDay), $this->getWeekNewUserRecords($w_id, $LastMonday, $LastSunDay), '周');
        $result['cancel']['number'] = $cancel;
        $result['cancel']['day'] = $this->inputElement($cancel, $this->getCancelUserRecords($w_id, $yesterday), '日');
        $result['cancel']['week'] = $this->inputElement($this->getWeekCancelUserRecords($w_id, $ThisMonday, $ThisSunDay), $this->getWeekCancelUserRecords($w_id, $LastMonday, $LastSunDay), '周');
        $result['growth']['number'] = $new - $cancel;
        $result['growth']['day'] = $this->inputElement($new - $cancel, $this->getNewUserRecords($w_id, $yesterday) - $this->getCancelUserRecords($w_id, $yesterday), '日');
        $result['growth']['week'] = $this->inputElement($this->getWeekNewUserRecords($w_id, $ThisMonday, $ThisSunDay) - $this->getWeekCancelUserRecords($w_id, $ThisMonday, $ThisSunDay), $this->getWeekNewUserRecords($w_id, $LastSunDay, $LastMonday) - $this->getWeekCancelUserRecords($w_id, $LastSunDay, $LastMonday), '周');
        $result['cumulative']['number'] = $this->getCumulative($w_id, $time);
        $result['cumulative']['day'] = $this->inputElement($this->getCumulative($w_id, $time), $this->getCumulative($w_id, $yesterday), '日');
        $result['cumulative']['week'] = $this->inputElement($this->getWeekCumulative($w_id, $ThisMonday, $ThisSunDay), $this->getWeekCumulative($w_id, $LastMonday, $LastSunDay), '周');
        return $result;

    }

    /**
     * @param Request $request
     * @return \EasyWeChat\Support\Collection|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * 修改用户备注
     */
    public function updateUserRemark(Request $request)
    {
        $id = $request->get('id');
        $remark = $request->get('remark');
        \DB::beginTransaction();
        try {
            $user = WechatUser::query()->where(['id' => $id])->first();
            if (!$user) {
                throw new \Exception('找不到该用户');
            }
            $wechat = WeChat::query()->where(['id' => $user->w_id])->first();
            if (!$wechat) {
                throw new \Exception('找不到该公众号');
            }
            $openPlatform = $this->openPlatform;
            $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
            $userService = $app->user;
            $userService->remark($user->open_id, $remark);
            $user->remark = $remark;
            if (!$user->save()) {
                throw new \Exception('修改失败');
            }
            \DB::commit();
            return response('修改成功', 200);
        } catch (\Exception $e) {
            \DB::rollBack();
            return response($e->getMessage(), 406);
        }

    }

    /**
     * 图片素材上传
     */
    public function imgUpload(Request $request)
    {
        $file = $request->file('file');
        $name = $request->get('file_name');
        // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
        $extension = $file->getClientOriginalExtension();
        $initpath = '/files_store/' . date('Y/m/d', time());
        //   dd($initpath);
        $savePath = public_path('') . $initpath;
        $filename = time() . rand(11111, 99999) . 'img.' . $extension;
        $file->move($savePath, $filename);
        $img = new WeChatImgSource();
        $img->imgName = $name;
        $img->imgPath = $initpath . '/' . $filename;
        if (!$img->save()) {
            return response('上传失败', 406);
        } else {
            return $img;
        }
    }

    /**
     * 音频素材上传
     */
    public function VoiceUpload(Request $request)
    {
        $file = $request->file('file');
        $name = $request->get('file_name');
        // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
        $extension = $file->getClientOriginalExtension();
        $initpath = '/files_store/voice/' . date('Y/m/d', time());
        //   dd($initpath);
        $savePath = public_path('') . $initpath;
        $filename = time() . rand(11111, 99999) . 'voice.' . $extension;
        $file->move($savePath, $filename);
        $voice = new WechatVoiceSource();
        $voice->voiceName = $name;
        $voice->voicePath = $initpath . '/' . $filename;
        if (!$voice->save()) {
            return response('上传失败', 406);
        } else {
            return $voice;
        }
    }

    /**
     * 视频素材上传
     */
    public function VideoUpload(Request $request)
    {
        $file = $request->file('file');
        $name = $request->get('file_name');
        $title = $request->get('title');
        $describe = $request->get('describe');
        // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
        $extension = $file->getClientOriginalExtension();
        $initpath = '/files_store/video/' . date('Y/m/d', time());
        //   dd($initpath);
        $savePath = public_path('') . $initpath;
        $filename = time() . rand(11111, 99999) . 'video.' . $extension;
        $file->move($savePath, $filename);
        $video = new WechatVideoSource();
        $video->videoName = $name;
        $video->videoPath = $initpath . '/' . $filename;
        $video->videoTitle = $title;
        $video->videoDescribe = $describe;
        if (!$video->save()) {
            return response('上传失败', 406);
        } else {
            return $video;
        }
    }

    /**
     * @param $paths
     * @param $w_id
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    private function imgArtUpload($paths, $w_id)
    {

        //   dd($w_id);
        try {
            $res = [];
            $wechat = WeChat::query()->where(['id' => $w_id])->first();
            if (!$wechat) {
                throw new \Exception('未找到公众号');
            }
            $openPlatform = $this->openPlatform;
            $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
            $material = $app->material;
            foreach ($paths as $path) {
                $result = $material->uploadArticleImage(public_path() . $path);
                if (!$result) {
                    throw new \Exception('上传失败');
                }
                $res[] = $result->url;
            }


            return $res;
        } catch (\Exception $e) {
            return response($e->getMessage(), 406);
        }

    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function SourceUpload(Request $request)
    {
        $w_id = $request->get('w_id');
        $id = $request->get('id');
        $type = $request->get('type');

        try {
            if (!$w_id) {
                throw new \Exception('微信获取失败');
            }
            $openPlatform = $this->openPlatform;
            $wechat = WeChat::query()->where(['id' => $w_id])->first();
            if (!$wechat) {
                throw new \Exception('未找到公众号');
            }
            $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
            $material = $app->material;
            switch ($type) {
                case 1;
                    $log = DB::table('wechat_img_logs')->where(['img_id' => $id, 'w_id' => $w_id])->first();
                    if (!$log) {
                        $img = DB::table('wechat_img_sources')->where(['id' => $id])->first();
                        $result = $material->uploadImage(public_path() . $img->imgPath);
                        if (!$result) {
                            throw new \Exception('上传失败');
                        }
                        $log = new WeChatImgLog();
                        $log->url = $result->url;
                        $log->media_id = $result->media_id;
                        $log->w_id = $w_id;
                        $log->img_id = $id;
                        if (!$log->save()) {
                            throw new \Exception('数据保存失败');
                        }
                    }
                    $res['media_id'] = $log->media_id;
                    return $res;
                    break;
                case 2;
                    $log = DB::table('wechat_art_logs')->where(['as_id' => $id, 'w_id' => $w_id])->first();
                    $ready_articles = $this->createArticles($id, $w_id, $material);
                    if (!$log) {

                        $result = $material->uploadArticle($ready_articles);
                        $log = new WechatArtLog();
                        $log->media_id = $result->media_id;
                        $log->w_id = $w_id;
                        $log->as_id = $id;
                        if (!$log->save()) {
                            throw new \Exception('数据保存失败');
                        }
                    } else {
                        foreach ($ready_articles as $key => $item) {
                            $material->updateArticle($log->media_id, $item, $key);
                        }
                    }
                    $res['media_id'] = $log->media_id;
                    return $res;
                    break;
                case 3;
                    $log = DB::table('wechat_voice_logs')->where(['voice_id' => $id, 'w_id' => $w_id])->first();
                    if (!$log) {
                        $voice = DB::table('wechat_voice_sources')->where(['id' => $id])->first();
                        $result = $material->uploadVoice(public_path() . $voice->voicePath);
                        if (!$result) {
                            throw new \Exception('上传失败');
                        }
                        $log = new WechatVoiceLog();
                        $log->media_id = $result->media_id;
                        $log->w_id = $w_id;
                        $log->voice_id = $id;
                        if (!$log->save()) {
                            throw new \Exception('数据保存失败');
                        }
                    }
                    $res['media_id'] = $log->media_id;
                    return $res;
                    break;
                case 4;
                    $log = DB::table('wechat_video_logs')->where(['video_id' => $id, 'w_id' => $w_id])->first();
                    if (!$log) {
                        $video = DB::table('wechat_video_sources')->where(['id' => $id])->first();
                        $result = $material->uploadVideo(public_path() . $video->videoPath, $video->videoTitle, $video->videoDescribe);
                        if (!$result) {
                            throw new \Exception('上传失败');
                        }
                        $log = new WechatVideoLog();
                        $log->media_id = $result->media_id;
                        $log->w_id = $w_id;
                        $log->video_id = $id;
                        if (!$log->save()) {
                            throw new \Exception('数据保存失败');
                        }
                    }
                    $res['media_id'] = $log->media_id;
                    return $res;
                    break;
            }
        } catch (\Exception $e) {
            return response($e->getMessage(), 406);
        }
    }

    /**
     * 获取所有公众号的所有用户
     */
    public function UserResult()
    {
        $wechat = WeChat::query()->get();
        $openPlatform = $this->openPlatform;
        \Log::info('执行获取记录');
        foreach ($wechat as $item) {
            $apps = $openPlatform->createAuthorizerApplication($item->authorizer_appid, $item->authorizer_refresh_token);
            $userService = $apps->user;
            $Wechat_users = $userService->lists();
            foreach ($Wechat_users['data']['openid'] as $user_item) {
                $user_logs = $userService->get($user_item);
                $wechat_user = WechatUser::withTrashed()->where(['open_id' => $user_item])->first();
                if (!$wechat_user) {
                    $wechat_user = new WechatUser();
                }
                //$logs = $user_logs->toArray();
                // \Log::info($logs);
                if (isset($user_logs->subscribe) && $user_logs->subscribe == 1) {
                    $wechat_user->w_id = $item->id;
                    $wechat_user->nick_name = $user_logs->nickname;
                    $wechat_user->sex = 2;
                    $wechat_user->city = $user_logs->city;
                    $wechat_user->country = $user_logs->country;
                    $wechat_user->province = $user_logs->province;
                    $wechat_user->headimgurl = $user_logs->headimgurl;
                    $wechat_user->open_id = $user_logs->openid;
                    $wechat_user->subscribe_time = $user_logs->subscribe_time;
                    $wechat_user->remark = $user_logs->remark;
                    $wechat_user->groupid = $user_logs->groupid;
                    $wechat_user->deleted_at = null;
                    $wechat_user->tagid_list = empty($user_logs->tagid_list) ? '' : json_encode($user_logs->tagid_list);
                    if (!$wechat_user->save()) {
                        \Log::info($wechat_user->getErrors());
                    } else {
                        \Log::info($wechat_user->toArray());
                    }
                }

            }

        }
    }

    /**
     * @param $contect
     * @param $w_id
     * @return mixed
     */
    public function ImgUrlChange($contect, $w_id)
    {
        //  $contects = $contect;
        $imgarr = $this->getimages($contect);
        // var_dump($contects);die;
        if ($imgarr) {
            $change = $this->imgArtUpload($imgarr, $w_id);
            // dd($this->changeUrlList($imgarr));
            $contect = str_replace($imgarr, $change, $contect);

        }
        return $contect;

    }

    /**
     * 回复消息
     * @param $appId
     * @param $open_id
     * @param $keywords
     * @return bool
     */
    public function replyMessage($appId, $open_id, $keywords)
    {

        // $openPlatform = $this->openPlatform;
        try {
            $wechat = WeChat::query()->where(['authorizer_appid' => $appId])->first();

            $openPlatform = $this->openPlatform;
            $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
            $contents = DB::table('reply_rules')->where(['w_id' => $wechat->id])->where('keywords', $keywords)->first();
            if ($contents) {
                switch ($contents->type) {
                    case 1;
                        $message = new Text(['content' => $contents->content]);
                        break;
                    case 2;
                        $message = new Material('image', $contents->source_id);
                        break;
                    case 3;
                        $message = new Material('mpnews', $contents->source_id);
                        break;
                    case 4;
                        $message = new Material('voice', $contents->source_id);
                        break;
                    case 5;
                        $message = new Material('mpvideo', $contents->source_id);
                        break;
                }
                $result = json_decode($app->staff->message($message)->to($open_id)->send());
                if ($result->errcode != 0) {
                    throw new \Exception('消息发送失败');
                }
            }

            // dd($message->user_open_id,$user);
            return true;
        } catch (\Exception $e) {
            \log::info($e->getMessage());
            return false;
        }

    }

    /**
     * @param Request $request
     */
    public function sendMass(Request $request)
    {
        $weChats = $request->get('weChats');
        $type = $request->get('type');
        $content = $request->get('content');
        $source_id = $request->get('source_id');
        try {
            if ($weChats && $type) {
                foreach ($weChats as $item) {
                    //  $this->MassToWechat($item,$type,$content,$source_id);
                    $log = new WechatMassLog();
                    $log->type = $type;
                    $log->w_id = $item;
                    $log->sender_id = Auth::user()->id;
                    $log->check_status = 1;
                    $log->source_id = $source_id;
                    $log->content = $content;
                    if (!$log->save()) {
                        throw new \Exception('记录保存失败');
                    }

                }
            } else {
                throw new \Exception('缺少参数');
            }
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '新增群发消息';
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            return response('发送记录添加成功', 200);
        } catch (\Exception $e) {
            return response($e->getMessage(), 406);
        }

    }

    public function checkMass(Request $request)
    {
        $log = $request->get('log');
        $status = $request->get('status');
        $reply = $request->get('reply');
        try {
            $mass = WechatMassLog::query()->where('id', $log)->first();
            if ($status == 2) {
                $this->MassToWechat($mass->w_id, $mass->type, $mass->content, $mass->source_id);
            }
            $mass->check_status = $status;
            $mass->status = 1;
            $mass->reply = $reply;
            $mass->checker_id = Auth::user()->id;
            if (!$mass->save()) {
                throw new  \Exception('记录修改失败');
            }
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = $mass->check_status == 2 ? '审核通过了一则群发消息' : '审核驳回了一则群发消息';
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            return response('发送成功', 200);
        } catch (\Exception $e) {
            return response($e->getMessage(), 406);
        }


    }

    protected function MassToWechat($appId, $type, $content, $source)
    {
        $wechat = WeChat::query()->where(['id' => $appId])->first();
        // dd($wechat,$appId);
        $openPlatform = $this->openPlatform;
        $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
        $broadcast = $app->broadcast;
        $material = $app->material;
        switch ($type) {
            case 1;
                $broadcast->sendText($content);
                break;
            case 2;
                $log = DB::table('wechat_img_logs')->where(['img_id' => $source, 'w_id' => $appId])->first();
                if (!$log) {
                    $img = DB::table('wechat_img_sources')->where(['id' => $source])->first();
                    $result = $material->uploadImage(public_path() . $img->imgPath);
                    if (!$result) {
                        throw new \Exception('上传失败');
                    }
                    $log = new WeChatImgLog();
                    $log->url = $result->url;
                    $log->media_id = $result->media_id;
                    $log->w_id = $appId;
                    $log->img_id = $source;
                    if (!$log->save()) {
                        throw new \Exception('数据保存失败');
                    }
                }
                $broadcast->sendImage($log->media_id);
                break;
            case 3;
                $log = DB::table('wechat_art_logs')->where(['as_id' => $source, 'w_id' => $appId])->first();
                $ready_articles = $this->createArticles($source, $appId, $material);
                if (!$log) {

                    $result = $material->uploadArticle($ready_articles);
                    $log = new WechatArtLog();
                    $log->media_id = $result->media_id;
                    $log->w_id = $appId;
                    $log->as_id = $source;
                    if (!$log->save()) {
                        throw new \Exception('数据保存失败');
                    }
                } else {
                    foreach ($ready_articles as $key => $item) {
                        $material->updateArticle($log->media_id, $item, $key);
                    }
                }
                $broadcast->sendNews($log->media_id);
                break;
            case 4;
                $log = DB::table('wechat_voice_logs')->where(['voice_id' => $source, 'w_id' => $appId])->first();
                if (!$log) {
                    $voice = DB::table('wechat_voice_sources')->where(['id' => $source])->first();
                    $result = $material->uploadVoice(public_path() . $voice->voicePath);
                    if (!$result) {
                        throw new \Exception('上传失败');
                    }
                    $log = new WechatVoiceLog();
                    $log->media_id = $result->media_id;
                    $log->w_id = $appId;
                    $log->voice_id = $source;
                    if (!$log->save()) {
                        throw new \Exception('数据保存失败');
                    }
                }
                $broadcast->sendVoice($log->media_id);
                break;
            case 5;
                $log = DB::table('wechat_video_logs')->where(['video_id' => $source, 'w_id' => $appId])->first();
                if (!$log) {
                    $video = DB::table('wechat_video_sources')->where(['id' => $source])->first();
                    $result = $material->uploadVideo(public_path() . $video->videoPath,$video->videoTitle,$video->videoDescribe);
                    if (!$result) {
                        throw new \Exception('上传失败');
                    }
                    $log = new WechatVideoLog();
                    $log->media_id = $result->media_id;
                    $log->w_id = $appId;
                    $log->video_id = $source;
                    if (!$log->save()) {
                        throw new \Exception('数据保存失败');
                    }
                }
                $broadcast->sendVideo($log->media_id);
                break;
        }
    }

    /**
     * @param $id
     * @param $w_id
     * @param $material
     * @return array
     * @throws \Exception
     */
    protected function createArticles($id, $w_id, $material)
    {
        $res = [];
        $articles = WechatArticle::query()->where(['sources_id' => $id])->get();
        foreach ($articles as $items) {
            $item['title'] = $items->title;
            $item['author'] = $items->author;
            $item['digest'] = $items->digest;
            $item['show_cover_pic'] = $items->show_cover_pic;
            $item['content'] = $this->ImgUrlChange($items->content, $w_id);
            $item['content_source_url'] = $items->content_source_url;
            if ($items->thumb_url) {
                $img = DB::table('wechat_img_sources')->where(['imgPath' => $items->thumb_url])->first();
                if (!$img) {
                    $img = new WeChatImgSource();
                    $img->imgPath = $items->thumb_url;
                    $img->imgName = $items->thumb_url;
                    $img->save();
                }
                $log = DB::table('wechat_img_logs')->where(['img_id' => $img->id, 'w_id' => $w_id])->first();
                if (!$log) {
                    $result = $material->uploadImage(public_path() . $img->imgPath);
                    if (!$result) {
                        throw new \Exception('上传失败');
                    }
                    $log = new WeChatImgLog();
                    $log->url = $result->url;
                    $log->media_id = $result->media_id;
                    $log->w_id = $w_id;
                    $log->img_id = $id;
                    if (!$log->save()) {
                        throw new \Exception('数据保存失败');
                    }

                }
                $item['thumb_media_id'] = $log->media_id;
            } else {
                $item['thumb_media_id'] = '';
            }
            $res[] = new Article($item);
        }
        return $res;
    }

    /**
     * @param $w_id
     * @param $key
     * @return array|null
     */

    protected function getRecordsByDays($w_id, $key)
    {
        $res = null;
        foreach ($this->days as $item) {
            if (strtotime($item) <= strtotime(" -1 day")) {
                switch ($key) {
                    case 1;
                        $res[] = $this->getNewUserRecords($w_id, $item);
                        break;
                    case 2;
                        $res[] = $this->getCancelUserRecords($w_id, $item);
                        break;
                    case 3;
                        $res[] = $this->getNewUserRecords($w_id, $item) - $this->getCancelUserRecords($w_id, $item);
                        break;
                    case 4;
                        $res[] = $this->getCumulative($w_id, $item);
                        break;
                    default;
                }
            } else {
                $res[] = null;
            }
        }
        return $res;
    }

    protected function getCumulative($w_id, $time)
    {
        $record = WechatCumulative::query()->where(['w_id' => $w_id, 'ref_date' => $time])->first();
        if ($record) {
            return $record['user_number'];
        } else {
            return 0;
        }
    }

    protected function getNewUserRecords($w_id, $time)
    {
        return WechatUserRecord::query()->where(['w_id' => $w_id, 'ref_date' => $time])->sum('new_user');
    }

    protected function getCancelUserRecords($w_id, $time)
    {
        return WechatUserRecord::query()->where(['w_id' => $w_id, 'ref_date' => $time])->sum('cancel_user');
    }

    protected function getWeekNewUserRecords($w_id, $begin, $end)
    {
        return WechatUserRecord::query()->where(['w_id' => $w_id])->whereBetween('times', [$begin, $end])->sum('new_user');

    }

    protected function getWeekCumulative($w_id, $begin, $end)
    {
        return WechatCumulative::query()->where(['w_id' => $w_id])->whereBetween('times', [$begin, $end])->avg('user_number');
    }

    protected function getWeekCancelUserRecords($w_id, $begin, $end)
    {
        return WechatUserRecord::query()->where(['w_id' => $w_id])->whereBetween('times', [$begin, $end])->sum('cancel_user');

    }

    protected function inputElement($new, $last, $danwei)
    {
        if ($new == $last || $new == 0) {
            return $danwei . '&nbsp;&nbsp;&nbsp;' . '— —';
        } elseif ($new < $last) {
            return $danwei . "&nbsp;&nbsp;&nbsp;" . number_format((($last - $new) / $new * 100), 1) . '% <i class=\'fa fa-level-down\'></i>';
        } else {
            return $danwei . "&nbsp;&nbsp;&nbsp;" . number_format((($new - $last) / $new * 100), 1) . '% <i class=\'fa fa-level-up\'></i>';
        }
    }

    protected function getimages($str)
    {
        // $ext = 'gif|jpg|jpeg|png|GIF|JPG|JPEG|PNG';
        preg_match_all('<img.*?src=\"(.*?.*?)\".*?>', $str, $matches);
        return $matches[1];
    }

    protected function GrabImage($url)
    {

        $dirPath = public_path('') .'/files_store/' . date('Y/m/d', time());
        if(file_exists($dirPath)){
            mkdir ($dirPath,0777,true);
        }
        $filename =  $dirPath. time() . rand(11111, 99999) . 'img.jpg';
        file_put_contents( $filename, file_get_contents($url));
        return $filename;

    }


}